$(function(){
	var code = randomString(4)
	$(".code_auth_num").text(code);
	
	//点击登录
	$(".login_button").click(function(){
		initDB();
	   var userName = $(".user_name_input").val()
	   var userPwd = $(".user_password_input").val()
	   var userCode = $(".code_auth_input").val()
	   if (userName.length == 0) {
		   alert("请输入用户名")
		   return
	   }
	   if (userPwd.length == 0) {
			alert("请输入密码")
			return
	   }
	   if (userCode.length == 0) {
			alert("请输入验证码")
			return
	   }
	   if (userPwd != "123456") {
		   alert("密码错误!")
		   return;
	   }
	   if (code === userCode) {
		   getUserList(function(userList) {
				checkLogin(userList, userName)
		   });
	   } else {
		   alert("请输入正确验证码")
		   return
	   }
	});
	
	//看不清?
	$(".no_see").click(function(){
		code = randomString(4)
		$(".code_auth_num").text(code);
	});
	
	//产生验证码
	function randomString(len) {
	   //chars中去除了容易混淆的字母或数字，例如O和0
	　　var chars = '1234567890'; 
	　　var maxPos = chars.length;
	　　var pwd = '';
	　　for (i = 0; i < len; i++) {
	　　　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
	　　}
	　　return pwd;
	}
	
	//
	function checkLogin(userList, userName) {
		if (userName === "admin"){
			currentUser.role = 1;
			localStorage.setItem("currentUser",JSON.stringify(currentUser));
			window.location.href = "../../main.html";
			return;
		}
		if (userList.length == 0) {
			alert("用户不存在");
			return;
		}
		
		var length = userList.length;
		var user = null;
		console.log(userList, userName);
		for (var i = 0; i < length; i++) {
			var u = userList.item(i);
			if (u.name === userName) {
				user = u;
				break;
			}
		}
		if (user) { //登录成功
			currentUser = user;
			localStorage.setItem("currentUser",JSON.stringify(currentUser));
			window.location.href = "../../main.html";
		} else {
			alert("用户不存在");
		}
		
	}
});